package com.project.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class Utils {
	public static final String DRIVER = "com.mysql.jdbc.Driver";
	public static final String URL = "jdbc:mysql://localhost:3306/project";
	public static final String NAME = "root";
	public static final String PASSWORD = "fyy123";
	public Connection conn = null;
	public PreparedStatement ps = null;
	public ResultSet rs = null;
	
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//公共连接方法
	public Connection getconn() {
		try {
			conn = DriverManager.getConnection(URL, NAME, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	//公共关闭方法
	public void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	//公共查询方法
	public ResultSet executeQuery(String sql,Object...parms) {
		conn = this.getconn();
		try {
			ps = conn.prepareStatement(sql);
			if(parms != null) {
				for(int i = 0;i<parms.length;i++) {
					ps.setObject(i+1, parms[i]);
				}
			}
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	//公共增删改
	public int executeUpdate(String sql,Object...parms) {
		conn = this.getconn();
		int line = 0;
		try {
			ps = conn.prepareStatement(sql);
			if(parms != null) {
				for(int i = 0;i<parms.length;i++) {
					ps.setObject(i+1, parms[i]);
				}
			}
			line = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			this.closeAll(conn, ps, rs);
		}
		return line;
	}

}
